package com.ylt.producer_consumer;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockPC {
    public static void main(String[] args) {
        Date02 date = new Date02();
        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    date.increment();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    date.decrement();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    date.increment();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 60; i++) {
                try {
                    date.decrement();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }, "D").start();
    }
}

//判断等待、业务、通知
class Date02 {  //资源类
    private int number = 0;
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    //+1
    public void increment() throws InterruptedException {
        lock.lock();
        try {
            //业务代码
            while (number != 0) {
                //等待
                condition.await();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    //-1
    public void decrement() {
        lock.lock();
        try {
            //业务代码
            while (number == 0) {
                //等待
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "=>" + number);
            //通知其他线程
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
